package com.taoym.voucher.xcx.callables;

import com.alibaba.fastjson.JSON;
import com.taoym.voucher.common.constant.CommonConstant;
import com.taoym.voucher.common.response.ActResp;
import com.taoym.voucher.common.utils.HttpClientUtils;
import com.taoym.voucher.xcx.domain.XcxPromotion;
import lombok.AllArgsConstructor;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * @coder taoym
 * @datetime 2021/8/26 12:01
 * @desc
 */
@AllArgsConstructor
public class ActGenerateCallable implements Callable<XcxPromotion> {
    /**
     * 租户信息
     */
    private final String apiKey;
    /**
     * 平台
     */
    private final Integer platform;
    /**
     * 系统活动信息
     */
    private final Integer actId;
    /**
     * 当前用户uid
     */
    private final String uid;
    /**
     * 要请求的http连接
     */
    private final String actUrl;

    @Override
    public XcxPromotion call() throws Exception {

        Map<String, Object> param = new HashMap<>();
        param.put("apikey", apiKey);
        param.put("sid", uid);
        param.put("relation_flag_name", CommonConstant.RELATION_FLAG_NAME);
        param.put("act_id", actId);
        String resp = HttpClientUtils.doPost(actUrl, JSON.toJSONString(param));
        ActResp actResp = JSON.parseObject(resp, ActResp.class);
        if (!ObjectUtils.isEmpty(actResp) && actResp.getCode().equals(1) && !ObjectUtils.isEmpty(actResp.getData())) {
            ActResp.Act act = actResp.getData();
            ActResp.WebAppInfo we_app_info = act.getWe_app_info();
            XcxPromotion xcxPromotion = new XcxPromotion();
            xcxPromotion.setActId(actId);
            xcxPromotion.setPlatform(platform);
            xcxPromotion.setCreateTime(LocalDateTime.now());
            xcxPromotion.setH5(act.getH5());
            xcxPromotion.setUid(uid);
            if (!ObjectUtils.isEmpty(we_app_info)) {
                xcxPromotion.setAppId(act.getWe_app_info().getApp_id());
                xcxPromotion.setMiniCode(act.getWe_app_info().getMiniCode());
                xcxPromotion.setPagePath(act.getWe_app_info().getPage_path());
            }
            return xcxPromotion;
        }
        return null;
    }
}
